home *** CD-ROM | disk | FTP | other *** search
- Path: hobbes.sco.COM!md
- From: md@sco.COM (Michael Davidson)
- Newsgroups: comp.lang.c
- Subject: Re: "#define" versus "const"
- Date: 1 Jan 1996 00:48:26 GMT
- Organization: The Santa Cruz Operation, Inc.
- Message-ID: <4c7b0q$7d6@hobbes.sco.COM>
- References: <4b97mt$rgp@wumpus.cc.uow.edu.au> <Crawford.819482696@voyager>
- NNTP-Posting-Host: execsrvr.research.sco.com
- Cc:
-
-
- In article <Crawford.819482696@voyager>, CRAWFORD <crawford@iac.net> wrote:
- >tp86@wumpus.cc.uow.edu.au (PAOPENG THEERADECH) writes:
- >> Could anybody here tell me what different between "#define" and "const"?.
- >>I saw "#define" is a normally use in C program, how about "const", what wrong
- >>with "const" and what the advantage of "#define" and disadvantage of "const"?.
- >
- > I've always heard that constants allow for better type
- >checking.
- >
-
- By "constants" I assume that you mean "variables which are declared to
- be const".
-
- Yes, they do allow better type checking and, for that reason, should
- be used when it is possible to do so.
-
- Unfortunately const was a (comparatively) recent addition to C which
- was not widely supported prior to the adoption of the ANSI standard
- and the semantics of const are less complete in C than one might like.
-
- In particular, "const" variables cannot be used in a "constant-expression"
- which is required in a number of places in C (to specify array bounds
- in a declarator, to specify the value in a "case" statement etc).
-
- So, in C, something like ...
- #define BufferSize 1024
-
- ... is usually more useful than ...
- const int BufferSize = 1024;
-
- ... since the former allows you to declare an array thus ...
- char my_buffer[BufferSize];
-
- ... and the latter does not.
-
- C++ does not have these restrictions and it is generally considered
- better C++ style to use "const" rather than "#define" in these
- circumstances.
-